﻿using PredictionBuilder.Utils;
using System;
using System.Collections.Generic;
using System.Text;

namespace PredictionBuilder.Attributes
{
    /// <summary>
    /// 忽略构建表达式特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public sealed class SkipBuildAttribute:Attribute
    {
        /// <summary>
        /// 期望作为哪种类型和目标值比较
        /// </summary>
        public Type TargetType { get;private set; }
        /// <summary>
        /// 忽略条件集合
        /// </summary>
        public List<object> Values { get;private set; }=new List<object>();
        /// <summary>
        /// 是否永远忽略此字段
        /// </summary>
        public bool IsAlwaysSkip { get;private set; }
        /// <summary>
        /// 使用此特性声明如果queryModel的属性值等于哪些值,则不生成表达式
        /// </summary>
        /// <param name="isAlwaysSkip">是否可以永久忽略此字段</param>
        /// <param name="targetType">作为哪种类型判断</param>
        /// <param name="values">忽略值集合(如果集合中有一条满足条件就会跳过条件构造)</param>
        public SkipBuildAttribute(bool isAlwaysSkip=false, Type targetType=null,params object[] values)
        {
            IsAlwaysSkip=isAlwaysSkip;
            TargetType = targetType;
            InitValues(values);
        }
        /// <summary>
        /// 是否可以跳过构建表达式
        /// </summary>
        /// <param name="compareValue"></param>
        /// <returns></returns>
        public bool CanSkip(object compareValue)
        {
            if (IsAlwaysSkip)
            {
                return IsAlwaysSkip;
            }
            bool flag = false;
            foreach(object value in Values)
            {
                if(Equals(compareValue, value))
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        private void InitValues(object[] values)
        {
            foreach (object value in values)
            {
                if (TargetType != null)
                {
                    try
                    {
                        var newValue = ExpressionHelper.SafeConversion(TargetType, value);
                        Values.Add(newValue);
                    }
                    catch
                    {
                        Values.Add(value);
                    }
                }
                else
                {
                    Values.Add(value);
                }
            }
        }
    }
}
